package com.atguigu.gmall.auth.service;


import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.exception.AuthException;
import com.atguigu.gmall.auth.feign.GmallUmsClient;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {
    @Autowired
    private GmallUmsClient gmallUmsClient;

    @Autowired
    private JwtProperties properties;

    public void login(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {
        //调用ums远程接口,根据登录名和密码查询用户
        ResponseVo<UserEntity> userEntityResponseVo = gmallUmsClient.queryUser(loginName, password);
        UserEntity userEntity = userEntityResponseVo.getData();

        //判断用户是否为空,如果为空则直接结束
        if (userEntity == null) {
            throw new AuthException("登录名或者密码错误");
        }

        //组装载荷内容
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userEntity.getId());
        map.put("userName", userEntity.getUsername());
        //为防止盗用,加入登录用户的ip地址
        map.put("ip", IpUtils.getIpAddressAtService(request));

        try {
            //生成jwt 类型的token
            String token = JwtUtils.generateToken(map, properties.getPrivateKey(), properties.getExpire());

            //将token放入cookie中
            CookieUtils.setCookie(request, response, properties.getCookieName(), token, properties.getExpire() * 60);
            //把用户昵称放入cookie中
            CookieUtils.setCookie(request, response, properties.getUnick(), userEntity.getNickname(),
                    properties.getExpire() * 60);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
